import { Injectable, Request } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Order, OrderStatusEnum } from '../entities/order.entity';
import { OrderCreateDto } from '../dto/orderCreate.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { GoodsService } from './goods.services';
import { UserService } from './user.service';
import { OrderUtils } from 'src/common/utils/order.utils';

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(Order)
    private readonly orderRepository: Repository<Order>,
    private readonly goodsService: GoodsService,
    private readonly userService: UserService,
  ) {}

  async getOrderList(request: Request) {
    const userInfo = await this.userService.getCurrentUserInfo(request);
    return await this.orderRepository.find({
      where: { createdBy: userInfo.userId },
    });
  }

  async createdOrder(orderCreateDto: OrderCreateDto, request: Request) {
    const order = new Order();
    const userInfo = await this.userService.getCurrentUserInfo(request);
    const goodsDetail = await this.goodsService.getGoodsById(
      orderCreateDto.goodsId,
    );
    // 商品单价
    order.goodsPrice = goodsDetail.price;
    // 商品数量
    order.goodsQuantity = orderCreateDto.goodsNum;
    // 总价
    order.totalPrice = goodsDetail.price * orderCreateDto.goodsNum;
    // 商品id
    order.goodsId = orderCreateDto.goodsId;
    // 下单时间
    order.orderTime = new Date();
    // 订单编码
    order.orderNo = OrderUtils.generateOrderCode(userInfo.userId);
    // 订单状态
    order.orderStatus = OrderStatusEnum.PENDING_PAY;
    order.createdBy = userInfo.userId;

    await this.orderRepository.save(order);

    return order.orderNo;
  }
}
